package com.bci.pwtz.controller.app;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.remote.BaseResponse;
import com.bci.pwtz.common.remote.ListResponse;
import com.bci.pwtz.common.remote.ObjResponse;
import com.bci.pwtz.common.remote.ReturnCode;
import com.bci.pwtz.common.remote.req.CompanyIdReq;
import com.bci.pwtz.common.remote.req.CompanyListReq;
import com.bci.pwtz.common.remote.req.CompanyReq;
import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.controller.AbstractController;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.model.Company;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.CompanyUserService;
import com.bci.pwtz.service.SensitiveWordService;

/**
 * 公司信息控制器类（CompanyController）
 * TODO
 * 
 * @author ICLNetwork Team
 * @version 3.0
 */
@Controller
@RequestMapping("/api/company")
public class CompanyAppController extends AbstractController
{
    // 自动扫描
    @Autowired
    private CompanyService companyService;
    
    @Autowired
    private SensitiveWordService sensitiveWordService;
    
    @Autowired
    private CompanyUserService companyUserService;

    /**
     * 公司信息
     * TODO
     * 
     * @param req
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    @ResponseBody
    public ListResponse<Company> search(HttpServletRequest request)
    {
        CompanyListReq req = null;
        ListResponse<Company> resp = new ListResponse<Company>();
        PaginationList<Company> list = new PaginationList<Company>();
        try
        {
            req = (CompanyListReq) getJsonToObj(request, CompanyListReq.class);
            if (req == null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(StringUtils.isBlank(req.getTimestamp()) || req.getUserId() == null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp()))
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            list = (PaginationList<Company>) companyService.findCompany(req.getCompanyName(),req.getPageSize(), req.getPage());
            Map<Long,Integer> refMap = companyUserService.getUserCompanyRef(req.getUserId());
            if (list != null)
            {
                for(Company company:list.getRecords())
                {
                    if(refMap.containsKey(company.getCompanyId()))
                        company.setRefStatus(refMap.get(company.getCompanyId()));
                }
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("获取公司信息成功");
                resp.setTimestamp(req.getTimestamp());
                resp.setObjs(list);
                //resp.setObjss(list.getRecords());
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("获取公司信息调用接口返回失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }
    
    
    
    /**
     * 公司信息
     * TODO
     * 
     * @param req
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public ListResponse<Company> list(HttpServletRequest request)
    {
        CompanyListReq req = null;
        ListResponse<Company> resp = new ListResponse<Company>();
        PaginationList<Company> list = new PaginationList<Company>();
        try
        {
            req = (CompanyListReq) getJsonToObj(request, CompanyListReq.class);
            if (req == null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(StringUtils.isBlank(req.getTimestamp()) || req.getUserId() == null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp()))
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            list = (PaginationList<Company>) companyService.findCompany(req.getCompanyName(), req.getPageSize(),req.getPage());
            if (list != null)
            {
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("查询公司列表成功");
                resp.setTimestamp(req.getTimestamp());
                resp.setObjs(list);
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("查询公司列表调用接口返回失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }

    /**
     * 新增公司信息
     * TODO
     * 
     * @param req
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public ObjResponse<Company> add(HttpServletRequest request)
    {
        CompanyReq req = null;
        ObjResponse<Company> resp = new ObjResponse<Company>();
        try
        {
            req = (CompanyReq) getJsonToObj(request, CompanyReq.class);
            if (req == null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(StringUtils.isBlank(req.getTimestamp()) || req.getUserId() == null || req.getCompany() ==null || req.getCompany().getCompanyName()==null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp()))
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            String companyName = req.getCompany().getCompanyName();
            int [] levels = {1,2,3};
            if(sensitiveWordService.matchContent(companyName, levels)){
                resp.setReturnCode(ReturnCode.PARAMETER_LENGTH_ERROR);
                resp.setReturnMsg("公司名称不合法");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            int companyNumByUser=companyService.selectCreateCompanyNumByUserId(req.getUserId());
            if(companyNumByUser>=PwtzConstants.MAX_CREATE_COMPANY_COUNT){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("用户能创建的公司数已为最大，不能再创建更多的公司");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            Company ret = companyService.add(req.getCompany(),1);
            if (ret !=null)
            {
                CompanyUser user=companyUserService.load(req.getUserId());
                if(user.getLastCompanyId()==null){
                    user.setLastCompanyId(ret.getCompanyId());
                    companyUserService.update(user);
                }
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("新增公司成功");
                resp.setTimestamp(req.getTimestamp());
                resp.setObj(ret);
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("新增公司调用接口返回失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }

    /**
     * 修改公司信息
     * TODO
     * 
     * @param req
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse update(HttpServletRequest request)
    {
        CompanyReq req = null;
        BaseResponse resp = new BaseResponse();
        int result = 0;
        try
        {
            req = (CompanyReq) getJsonToObj(request, CompanyReq.class);
            if (req == null || StringUtils.isBlank(req.getTimestamp()) || req.getUserId() == null|| req.getCompany() ==null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp()))
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            result = companyService.update(req.getCompany());
            if (result > 0)
            {
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("修改公司信息成功");
                resp.setTimestamp(req.getTimestamp());
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("修改公司信息调用接口返回失败");
                resp.setTimestamp(req.getTimestamp()); 
            }
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        System.out.println(req.getCompany());
        return resp;
    }

    /**
     * 删除公司信息
     * TODO
     * 
     * @param req
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse delete(HttpServletRequest requet)
    {
        CompanyIdReq req = null;
        BaseResponse resp = new BaseResponse();
        int result = 0;
        try
        {
            req = (CompanyIdReq) getJsonToObj(requet, CompanyIdReq.class);
            if (req == null || StringUtils.isBlank(req.getTimestamp()) || req.getUserId() == null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp()))
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            result = companyService.delete(req.getCompanyId());
            // company = companyService.delete(companyId);
            if (result > 0)
            {
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("删除公司信息成功");
                resp.setTimestamp(req.getTimestamp());
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("删除公司信息调用接口返回失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }

    /**
     * 根据公司ID获取公司信息
     * TODO
     * 
     * @param req
     * @return
     */
    @RequestMapping(value = "/load", method = RequestMethod.POST)
    @ResponseBody
    public ObjResponse<Company> load(HttpServletRequest requet)
    {
        CompanyIdReq req = null;
        ObjResponse<Company> resp = new ObjResponse<Company>();
        Company company = new Company();
        // String companyId = "";
        try
        {
            req = (CompanyIdReq) getJsonToObj(requet, CompanyIdReq.class);
            if (req == null || StringUtils.isBlank(req.getTimestamp()) || req.getUserId() == null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp()))
            {
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
            {
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            company = companyService.load(req.getCompanyId());
            if (company != null)
            {
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("获取公司信息成功");
                resp.setTimestamp(req.getTimestamp());
                resp.setObj(company);
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("获取公司信息调用接口返回失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }
}